#include "httplib.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <deque>
#include <unistd.h>
#include "json.hpp"

using json = nlohmann::json;
//int id = random()%80000000;
int id = 816000000;

//struct dirent
//{
//    long d_ino; /* inode number 索引节点号 */
//    off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
//    unsigned short d_reclen; /* length of this d_name 文件名长 */
//    unsigned char d_type; /* the type of d_name 文件类型 */
//    char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名，最长255字符 */
//};

std::deque<std::string> filenameDeque;
int fileCount = 0;

int readFileList(char *basePath)
{

    printf("enter into path :%s\n",basePath);
    DIR *dir;
    struct dirent *ptr;
    char base[1000];

    if ((dir=opendir(basePath)) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }

    while ((ptr=readdir(dir)) != NULL)
    {
        printf("ptr->d_name: %s\n",ptr->d_name);
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8)    ///file
        {
            printf("d_name: %s,filename: %s,fileCount: %d\n",basePath,ptr->d_name,++fileCount);
            filenameDeque.push_back(ptr->d_name);
        }
        else if(ptr->d_type == 10)    ///link file
            printf("d_name:%s/%s\n",basePath,ptr->d_name);
        else if(ptr->d_type == 4)    ///dir
        {
            memset(base,'\0',sizeof(base));
            strcpy(base,basePath);
            strcat(base,"/");
            strcat(base,ptr->d_name);
            readFileList(base);
        }
    }
    closedir(dir);
    return 1;
}
char *randstr(char *str, const int len)
{
    srand(time(NULL));
    int i;
    for (i = 0; i < len; ++i)
    {
        switch ((rand() % 3))
        {
            case 1:
                str[i] = 'A' + rand() % 26;
                break;
            case 2:
                str[i] = 'a' + rand() % 26;
                break;
            default:
                str[i] = '0' + rand() % 10;
                break;
        }
    }
    str[++i] = '\0';
    return str;
}


void requestpost(std::string paraStr){

//    httplib::Client cli("http://101.251.207.220", 888);
//    httplib::Client cli("http://101.251.207.220:888");


    id++;

    std::string taskNum = std::to_string(id);

    std::string file_path_in = "/nfs/in/样本1/免费/要闻早点报/";
    std::string file_path_out = "/nfs/cluster/样本1/免费/体要闻早点报/";
    file_path_in += paraStr;
    file_path_out += paraStr;

//    httplib::Client cli("http://101.251.207.211:8080");
    httplib::Client cli("101.251.219.205");

    json  oJson;
    oJson["file_path_in"] = file_path_in; //"/nfs/in/样本2/性能测试/100h-2/杨富江、乔乔《千里共良宵，新春云团圆》.mp3";
    oJson["file_path_out"] = file_path_out; //"/nfs/out/正午60分/韩外交部高官赴伊朗谈释放遭扣油轮.mp3";
    oJson["state"] = "1";
    oJson["task_number"] = taskNum;
    oJson["reserve"] = "";
    std::string body = oJson.dump();
    std::cout << body << std::endl;
    std::cout << "-------------------------------------------------------------------" << std::endl;

//    auto res = cli.Post("/cmscallback", s, "application/json");
//    auto res = cli.Post("/yt/r0/api/wtermark/fromcms/postfilestate", body, "application/json");
    auto res = cli.Post("/api/wtermark/fromcms/postfilestate", body, "application/json");
//    auto res = cli.Post("/cmscallback", body, "text/plain");

    if (res == nullptr){
        perror("res is null \n");
    } else{
        std::cout << res->status << "\t" << res->body << "\n" ;
    }
}



void getPath(){
    std::cout << "Hello, GetFilesName!" << std::endl;

    DIR *dir;
    char basePath[1000];

    ///get the current absoulte path
    memset(basePath,'\0',sizeof(basePath));
    getcwd(basePath, 999);
    printf("the current dir is : %s\n",basePath);

    ///get the file list
    memset(basePath,'\0',sizeof(basePath));
    strcpy(basePath,"/nfs/in/样本1/免费/要闻早点报/");
    readFileList(basePath);

    std::cout <<"The total file number " << filenameDeque.size()<< "\n";

    while (!filenameDeque.empty()){
//        if (!filenameDeque.empty()){
        std::cout << "The file sequence is  " << filenameDeque.size() << "\n";
//        << " file from deque: " << filenameDeque.front() << "\n";

        std::cout << filenameDeque.front() << "\n";

            requestpost(filenameDeque.front());

//            requestYuntingWithParameter(filenameDeque.front());
        std::this_thread::sleep_for(std::chrono::milliseconds (1));
//        printf("wake up \n");

        filenameDeque.pop_front();
    }
}

void requestServer(int val)
{
    while (1){
//// HTTPS
//    httplib::Client cli("https://cpp-httplib-server.yhirose.repl.co");

        std::cout << "file number is  " << filenameDeque.size() << " file from deque: " << filenameDeque.front() << "\n";

//        requestYuntingWithParameter(filenameDeque.front());

        filenameDeque.pop_front();

        std::this_thread::sleep_for(std::chrono::milliseconds (50));
        printf("wake up \n");
    }

}


int main() {
    std::cout << "Hello, World!" << std::endl;
    getPath();

//    std::thread threadReq(requestServer,1);
//
//    threadReq.join();


    return 0;
}


void requestYuntingWithParameter(std::string paraStr){

//    std::string sendHeader = "http://101.251.207.211:8081/";
//    std::string sendHeader = "http://101.251.207.211:8080/yt/r0/api/wtermark/fromcms/postfilestate";
//    std::string sendHeader = "http://101.251.207.220:888";
//    sendHeader += paraStr;
//    std::cout << sendHeader << "\n";
//    httplib::Client cli("http://cpp-httplib-server.yhirose.repl.co");
//    httplib::Client cli(sendHeader);
//    httplib::Client cli("http://101.251.207.220", 888);
//    auto res = cli.Get("/cmscallback");

//    auto res = cli.Get("/hi");

    std::string file_path_in = "/nfs/in/样本/免费/";
    std::string file_path_out = "/nfs/out/样本/免费/";
    file_path_in += paraStr;
    file_path_out += paraStr;

//    httplib::Params params{
//            {"file_path_in",file_path_in},
//            {"file_path_out",file_path_out},
//            {"state","1"},
//            {"task_number","6626f3334f81ff937"},
//            {"reserve",""}
//    };

    httplib::Client cli("http://101.251.207.211:8080/yt/r0/api/wtermark/fromcms/postfilestate", 8081);

    std::string body = "{\n"
                       "\"file_path_in\":\"file_path_in\",\n"
                       "\"file_path_out\":\"file_path_out\",\n"
                       "\"state\":\"1\",\n"
                       "\"task_number\":\"6626f3334f81ff940\",\n"
                       "\"reserve\":""}";
    body = "{ file: path}";
    auto res = cli.Post("/post", body, "application/json");
//    assert(res->status == 200);

//    auto res = cli.Post("/post", params);

    if (res == nullptr){
        perror("res is null \n");
    } else{
        std::cout << res->status << "\t" << res->body << "\n" ;
    }

}


/*
int main(void)
{
    std::cout << "Hello, GetFilesName!" << std::endl;

    DIR *dir;
    char basePath[1000];

    ///get the current absoulte path
    memset(basePath,'\0',sizeof(basePath));
    getcwd(basePath, 999);
    printf("the current dir is : %s\n",basePath);

    ///get the file list
    memset(basePath,'\0',sizeof(basePath));
    strcpy(basePath,"/root/projects/test/GetfilesName/cmake-build-debug");
    readFileList(basePath);
    return 0;
}
*/



